package com.example.roamio.service.impl;

import com.example.roamio.common.Result;
import com.example.roamio.entity.User;
import com.example.roamio.interceptor.LoginInterceptor;
import com.example.roamio.repository.UserRepository;
import com.example.roamio.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

    private final UserRepository userRepository;

    @Override
    public Integer getCurrentUserId() {
        Integer userId = LoginInterceptor.CURRENT_USER_ID.get();
        if (userId == null) {
            throw new IllegalStateException("当前用户未登录");
        }
        return userId;
    }

    @Override
    public Result<String> updateUsername(Integer userId, String newUsername) {
        Optional<User> optionalUser = userRepository.findById(userId);
        if (optionalUser.isEmpty()) {
            return Result.fail(404, "用户不存在");
        }

        User user = optionalUser.get();
        user.setUsername(newUsername);
        userRepository.save(user);
        return Result.success("用户名更新成功");
    }
}
